/*
 * UCardImageServlet.java
 *
 * Created on June 5, 2007, 6:00 PM
 */

package wap.rockvilletech.util.imaging;



import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import wap.rockvilletech.portal.SystemProperty;


import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 *
 * @author tazzix
 * @version
 */
@SuppressWarnings("serial")
public class ImageResizeServlet extends HttpServlet {
    
	private static final Logger log = Logger.getLogger(ImageResizeServlet.class);
	private static final String IMAGE_JPG = "jpeg";
    private static boolean isParamsLoaded = false;
    private static String path_internal_dir = "";
    private static String path_sample_dir = "";
    private static String path_portal_images_dir = "";


    
    @Override
	public void init() throws ServletException {
        if(!isParamsLoaded) {
        	try {
                    //--path_internal_dir = new java.io.File(getServletContext().getRealPath("")).toString();
	            path_internal_dir = new java.io.File(getServletContext().getRealPath("")).toString() +"/images/"; //to read from main context
	            //--path_sample_dir = getServletConfig().getServletContext().getInitParameter("basePath").toString();
	            path_sample_dir = SystemProperty.getProperty("basePath"); // D:\\usr\\ufone\\sample\\
	            //--path_portal_images_dir = getServletConfig().getServletContext().getInitParameter("portal_images").toString();
	            path_portal_images_dir = SystemProperty.getProperty("portal_images");
	            isParamsLoaded = true;
	            log.info("init parameters loaded!");
        	} catch(Exception e) {        		
        	}            
        }
	}

	public ImageResizeServlet() {
        
    }
    
    /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {        
        
        String anim = "", img = "", strS = "", path = "", useRepository = "";
        int newWidth = 0;
        ServletOutputStream sos = null;
        byte [] data = null;
        BufferedImage image = null;
        try {
            anim = request.getParameter("anim") != null ? request.getParameter("anim").toString() : "";
            img = request.getParameter("img") != null ? request.getParameter("img").toString() : "";
            strS = request.getParameter("s") != null ? request.getParameter("s").toString() : "";
            newWidth = Integer.parseInt( request.getParameter("w") != null ? request.getParameter("w").toString() : "0" );
            useRepository = request.getParameter("repo") != null ? request.getParameter("repo").toString() : "";
            //--log.debug("Get Request Params : img="+img+"useRepository="+useRepository);
            // programmer can set the repositor path, from where to get the images
            if ( useRepository != null && useRepository.equalsIgnoreCase("INTERNAL")) {
                // use the websites internal image directory
                path = path_internal_dir;
                //--log.debug("INTERNAL path="+path);
            }
            else if ( useRepository != null && useRepository.equalsIgnoreCase("HTTP")) {
                // images will directly be downloaded from web
                // This funcationality is not yet implemented
                path = "";
            }
            else if (useRepository != null && useRepository.equalsIgnoreCase("PI")) {
                // use the portal_images directory
                path = path_portal_images_dir;
                //--log.debug("PI path="+path);
            }
            else {
                // use the sample repository
                path = path_sample_dir;
                //--log.debug("path_sample_dir path="+path);
            }
            
            //path=new java.io.File(getServletContext().getRealPath("")).toString();
            if(!path.endsWith("\\") && !path.endsWith("/") && !(useRepository.equalsIgnoreCase("HTTP")) )
                path += "/";

            if( img.indexOf(".gif") > 0 ) {
                try {
                	response.setContentType("image/gif");
                	AnimatedGifEncoder.genImage( path+img, response.getOutputStream(), strS, newWidth );
                }
                catch(Exception e) {
                    log.error("Error Image: "+ path + img, e );
                }
            }
            
            response.setContentType("image/jpeg");
            image = ImageIO.read(new File(path+img));
            if( image == null ) {
                log.debug("Image Not Available PATH IMGSERV = "+path+img+" ");
                return;
            }
            data = scaleImage(image, newWidth, -1);                        
            if( data != null ) {
                try {
                    sos = response.getOutputStream();            
                    sos.write(data);                
                	sos.flush();
                } catch(Exception e) {                	
                }
            }
        }
        catch( Exception e ) {
            log.error("Error Image: "+ path + img, e );
        } finally {
        	try {
	        	if(sos != null) {
	        		sos.close();
	        	}
	        	image = null;
	        	data = null;
            } catch(Exception e) {}
        }
    }
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    {
        processRequest(request, response);
    }
    
    /** Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }
    
    private byte[] scaleImage(Image image, int p_width, int p_height) throws Exception {
    
		int thumbWidth = p_width;
		int thumbHeight = p_height;

		// Make sure the aspect ratio is maintained, so the image is not skewed
		int imageWidth = image.getWidth(null);
		int imageHeight = image.getHeight(null);
		double imageRatio = (double) imageWidth / (double) imageHeight;
		if (p_height == -1) {
			thumbHeight = (int) ((double) thumbWidth / imageRatio);
		} else {
			double thumbRatio = (double) thumbWidth / (double) thumbHeight;
			if (thumbRatio < imageRatio) {
				thumbHeight = (int) (thumbWidth / imageRatio);
			} else {
				thumbWidth = (int) (thumbHeight * imageRatio);
			}
		}
		// Draw the scaled image
		BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight,
				BufferedImage.TYPE_INT_RGB);
		Graphics2D graphics2D = thumbImage.createGraphics();
		graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
				RenderingHints.VALUE_INTERPOLATION_BILINEAR);
		graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);

		// Write the scaled image to the outputstream
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
		JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
		int quality = 100; // Use between 1 and 100, with 100 being highest quality
//		quality = Math.max(0, Math.min(quality, 100));
		param.setQuality((float) quality / 100.0f, false);
		encoder.setJPEGEncodeParam(param);
		encoder.encode(thumbImage);
		ImageIO.write(thumbImage, IMAGE_JPG, out);
		return out.toByteArray();
    }         
}
